/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ouwen.smartpay.service.chain.slotchain;

import com.ouwen.smartpay.service.chain.slots.DefaultSlotChainBuilder;
import com.ouwen.smartpay.service.chain.spi.SpiLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 *@author <a href="http://youngitman.tech">青年IT男</a>
 *@version v1.0.0
 *@className SlotChainProvider
 *@description SlotChain提供者
 *@JunitTest: {@link  }
 *@date 11:10 2020-04-22
 *
**/
public final class SlotChainProvider {

    private static Logger logger = LoggerFactory.getLogger(SlotChainProvider.class);

    private static volatile SlotChainBuilder slotChainBuilder = null;

    /***
     *
     * 构建 {@link ProcessorSlotChain}
     *
     * @author liyong
     * @date 11:07 2020-04-22
     * @param
     * @exception
     * @return ProcessorSlotChain
     **/
    public static ProcessorSlotChain newSlotChain() {

        if (slotChainBuilder != null) {
            return slotChainBuilder.build();
        }

        //通过SPI获取SlotChainBuilder
        slotChainBuilder = SpiLoader.loadFirstInstanceOrDefault(SlotChainBuilder.class, DefaultSlotChainBuilder.class);

        if (slotChainBuilder == null) {
            logger.warn("[SlotChainProvider] Wrong state when resolving slot chain builder, using default");
            slotChainBuilder = new DefaultSlotChainBuilder();
        } else {
            logger.info("[SlotChainProvider] Global slot chain builder resolved: {}",slotChainBuilder.getClass().getCanonicalName());
        }
        return slotChainBuilder.build();
    }

    private SlotChainProvider() {
    }
}
